package com.hqq.exercise.recursion_loop;

/**
 * Fibonacci 斐波那契数列
 * 题目描述:
 * 输入n 求斐波那契数列的第n项
 * 0 1 1 2 3 5 7 13 20...
 * Created by heqianqian on 2017/8/10.
 */
public class Fibonacci {

    public static int getItemByRecursion(int index) {
        if (index == 1) {
            return 1;
        }
        if (index == 0) {
            return 0;
        }
        return getItemByRecursion(index - 1) + getItemByRecursion(index - 2);
    }

    public static int getItemByLoop(int index) {
        int result = 0;
        int firstItem = 0, secondItem = 1;
        if (index == 1) {
            return secondItem;
        }
        for (int i = 2; i <= index; i++) {
            result = firstItem + secondItem;
            firstItem = secondItem;
            secondItem = result;
        }
        return result;
    }

}

